/**
 * Created by wangdi on 4/11/16.
 * 发现
 */
'use strict';

import React, {Component} from 'react';
import {Text, View, StyleSheet, Platform, RefreshControl, ScrollView, ToastAndroid, Image, Dimensions, PixelRatio, Alert, AlertIOS} from 'react-native';
import px2dp from '../util/px2dp';
import theme from '../config/theme';
import computeTime from '../util/computeTime';
import SearchBar from '../component/SearchBar';
import Swiper from 'react-native-swiper';
import ImageButton from '../component/ImageButtonWithText';
import ListView from '../component/SimpleListView';

const bannerImages = [
    require('../image/banner1.jpg'),
    require('../image/banner2.png')
];

const imgBtnImages = [
    require('../image/trend.png'),
    require('../image/rank.png'),
    require('../image/hot.png')
];

export default class CompassFragment extends Component{
    constructor(props){
        super(props);
        this.state = {
            refreshing: true,
            loadedData: false,
            dataBlob: [],
            btnName: ['沸点','贡献榜','本周最热']
        }
    }

    render(){
        return(
            <View style={styles.container}>
                <SearchBar onPress={this._searchButtonCallback.bind(this)}/>
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            colors={['red','#ffd500','#0080ff','#99e600']}
                            tintColor={theme.themeColor}
                            title="Loading..."
                            titleColor={theme.themeColor}
                        />
                    }>
                    {/* <Swiper
                        height={px2dp(130)}
                        autoplay={true}
                        bounces={true}>
                        <View style={styles.slide}>
                            <Image style={styles.image} source={bannerImages[0]} resizeMode="stretch"/>
                        </View>
                        <View style={styles.slide}>
                            <Image style={styles.image} source={bannerImages[1]} resizeMode="stretch"/>
                        </View>
                    </Swiper> */}
                    <View style={styles.imageBtnLine}>
                        {this.state.btnName.map((item, index) => {
                            return(
                            <ImageButton
                                key={index}
                                image={imgBtnImages[index]}
                                imgSize={px2dp(35)}
                                text={item}
                                color="#000"
                                btnStyle={styles.imgBtn}
                                onPress={this._imageButtonCallback.bind(this, index)}/>
                            )})
                        }
                    </View>
                    { this._renderListView() }
                </ScrollView>
            </View>
        );
    }

    _onRefresh() {
        this.setState({refreshing: true});
        this._fetchData();
    }

    _searchButtonCallback(){

    }

    _imageButtonCallback(position){
        this._alert();
    }

    _renderListView(){
        if(!this.state.refreshing || this.state.loadedData) {
            return (
                <ListView isRenderHeader={true} contents={this.state.dataBlob}/>
            );
        }
    }

    _getTag(data) {
        let tagArray = [];
        if(data){
            for(let i in data){
                let title = data[i].title
                tagArray.push(title)
            }
        }else{
            tagArray.push('暂无')
        }
        return tagArray
    }

    _fetchData(){
        fetch('https://timeline-merger-ms.juejin.im/v1/get_entry_by_rank?src=web&uid=58f96a731b69e6005882de27&device_id=1510821442805&token=eyJhY2Nlc3NfdG9rZW4iOiIzNlZvT0xEdXJKaW11SnFRIiwicmVmcmVzaF90b2tlbiI6ImlKNThYUGYxNlZISEEzamEiLCJ0b2tlbl90eXBlIjoibWFjIiwiZXhwaXJlX2luIjoyNTkyMDAwfQ%3D%3D&limit=20&category=' + '5562b410e4b00c57d9b94a92')
            .then((response) => response.json())
            .then((responseData) => {
                console.log(responseData)
                // let data = responseData.data;
                let listData = responseData.d;
                let list = listData.entrylist
                var dataBlob = []; //创建数据model数组
/**
 * Objects are not valid as a React child (found: object with keys {ngxCachedTime, ngxCached, title, id}). If you meant to render a collection of children, use an array instead.
 * 使用
 */
                for (let i in list) {
                    let info = {
                        // author: list[i].author,
                        // checkStatus: list[i].checkStatus,
                        // createdAt: list[i].createdAt,
                        // english: list[i].english,
                        // entryView: list[i].entryView,
                        // gfw: list[i].gfw,
                        // hot: list[i].hot,
                        // hotIndex: list[i].hotIndex,
                        // isCollected: list[i].isCollected,
                        // lastCommentTime: list[i].lastCommentTime,
                        // ngxCachedTime: list[i].ngxCachedTime,
                        // objectId: list[i].objectId,
                        // original: list[i].original,
                        // originalUrl: list[i].originalUrl,
                        // rankIndex: list[i].rankIndex,
                        // subscribersCount: list[i].subscribersCount,
                        // summaryInfo: list[i].summaryInfo,
                        // type: list[i].type,
                        // updatedAt: list[i].updatedAt,
                        // verifyCreatedAt: list[i].verifyCreatedAt,
                        // verifyStatus: list[i].verifyStatus,
                        time: computeTime(list[i].buildTime), //创建时间
                        category: list[i].category, //分类
                        collectionCount: list[i].collectionCount, //点赞人数
                        commentsCount: list[i].commentsCount, //评论地址
                        content: list[i].content, //内容
                        screenshot: list[i].screenshot ? list[i].screenshot : null, //快照
                        tags: this._getTag(list[i].tags), // 标签
                        title: list[i].title, //title
                        user: list[i].user, //作者
                        viewsCount: list[i].viewsCount, //查看人数
                        url: list[i].originalUrl //地址
                    }
                    dataBlob.push(info)
                }

                this.setState({
                    dataBlob: dataBlob,
                    loadedData: true,
                    refreshing: false
                });
            }).done();

    }

    componentDidMount(){
        this._fetchData();
    }

    _alert(){
        if(Platform.OS === 'android') {
            Alert.alert(
                'Message',
                "This function currently isn't available",
                [{text: 'OK', onPress: () => {}}]
            );
        }else if(Platform.OS === 'ios'){
            AlertIOS.alert(
                'Message',
                "This function currently isn't available",
                [{text: 'OK', onPress: () => {}}]
            );
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: theme.pageBackgroundColor
    },
    slide: {
        
    },
    image: {
        height: px2dp(130),
        width: Dimensions.get('window').width
    },
    imageBtnLine:{
        flexDirection: 'row',
        backgroundColor: '#fff',
        alignItems: 'center',
        borderBottomWidth: 1/PixelRatio.get(),
        borderBottomColor: '#c4c4c4'
    },
    imgBtn: {
        height: px2dp(80),
        width: Dimensions.get('window').width/3,
    }
});
